package ys.db2es.controller;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ys.db2es.pojo.Order;
import ys.db2es.service.OrderService;
import ys.db2es.utils.EsUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order2es")
public class Order2Es {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private OrderService service;

    private String index = "order";

    @GetMapping("/creatIndex")
    public Object createIndex() throws IOException {
        Map<String, String[]> mapping = new HashMap<>();
        mapping.put("name", new String[]{"type=text", "analyzer=ik_max_word", "index=true", "store=false"});
        mapping.put("pid", new String[]{"type=integer"});
        mapping.put("uid", new String[]{"type=integer"});
        return EsUtil.createIndex(restHighLevelClient, index, 5, 1, mapping);

    }

    @GetMapping("/putDocs")
    public Object putDocs() throws IOException {
        List<Order> users = service.findAll();
        return EsUtil.putDocs(restHighLevelClient, index, users);
    }

    @GetMapping("/getAllInEs")
    public Object getAllInEs() throws IOException {
        List<Order> orders = EsUtil.getAllDocs(restHighLevelClient, index, Order.class);
        orders.stream().forEach(System.out::println);
        return orders;
    }
}
